import { systemParamValue } from "@/api/parameter";
import { messageError } from "@/util/element-ui";
import acceptTypes from "@/util/fileJson";
/**
 * 文档预览接入
 * 文档地址：https://file.kkview.cn/integrated
 * @param {*} attUrl
 */
export async function kkFileView(attUrl) {
  if (!attUrl) {
    messageError("文件地址错误");
    return;
  }
  const _name = attUrl.split(".");
  const fileType = _name[_name.length - 1];
  if (acceptTypes.length && !acceptTypes.includes(fileType.toLowerCase())) {
    window.open(attUrl);
    return;
  }
  const kkService = await systemParamValue({ paramKey: "FILE_PREVIEW_URL" });
  const baseUrl = encodeURIComponent(toBase64(attUrl));
  const kkFileView = `${kkService}?url=${baseUrl}`;
  window.open(kkFileView);
}

/**
 * base64 转码
 * @param {*} url
 * @returns
 */
export function toBase64(url) {
  const encoder = new TextEncoder();
  const data = encoder.encode(url);
  const base64String = btoa(String.fromCharCode(...data));
  return base64String;
}

/**
 * 文件是否支持预览
 * @param {*} attUrl
 * @returns
 */
export function canPreview(attUrl) {
  try {
    const _name = attUrl.split(".");
    const fileType = _name[_name.length - 1];
    if (acceptTypes.length && acceptTypes.includes(fileType.toLowerCase())) {
      return true;
    }
  } catch {
    return false;
  }
}
